import { _decorator, Component, Node ,input,Input } from 'cc';
const { ccclass, property } = _decorator;
let danwei = 10;
@ccclass('GameManager')
export class GameManager extends Component {
    @property({ type: Node })
    MainCamera: Node | null = null;

    @property({ type: Node })
    XiaoChe: Node | null = null;

    Player_move = {
        left: false,
        right: false,
    }

    onKeyUp(event: any){
        console.log('key down', event); 
        if(event.keyCode == 37){ ///向左
            this.Player_move.left = false;
        }
        if(event.keyCode == 39){ ///向右
            this.Player_move.right = false;
        }
    }

    onKeyDown(event: any){
        console.log('key down', event); 
        if(event.keyCode == 37){ ///向左
            this.Player_move.left = true;
        }
        if(event.keyCode == 39){ ///向右
            this.Player_move.right = true;
        }
    }

    protected onLoad(): void {
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    start() {
        
    }

    protected onDestroy(): void {
        input.off(Input.EventType.KEY_UP, this.onKeyUp,this);
        input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
    }

    update(deltaTime: number) {
        if(this.MainCamera){
            let pos = this.MainCamera.getPosition();
            this.MainCamera.setPosition(pos.x,pos.y,pos.z-deltaTime*danwei);
            // this.MainCamera.setPositionZ(pos_z+deltaTime*danwei);
        }
        if(this.XiaoChe){
            let pos = this.XiaoChe.getPosition();
            let pos_x = pos.x;
            // let pos_x_num = Math.max(-2.8, Math.min(2.8, pos_x));
            // console.log('pos_x_num', pos_x_num);
            if(this.Player_move.left && !this.Player_move.right){
                let pos_x_num = pos.x-deltaTime*danwei;
                if(pos_x_num <= -2.8){
                    pos_x_num = -2.8; 
                }
                this.XiaoChe.setPosition(pos_x_num,pos.y,pos.z-deltaTime*danwei);
            }else if(this.Player_move.right && !this.Player_move.left){
                let pos_x_num = pos.x+deltaTime*danwei;
                if(pos_x_num >= 2.8){
                    pos_x_num = 2.8; 
                }
                this.XiaoChe.setPosition(pos_x_num,pos.y,pos.z-deltaTime*danwei);
            }else{
                this.XiaoChe.setPosition(pos.x,pos.y,pos.z-deltaTime*danwei);
            }
        }
    }

    onReset() {
        
    }
}


          

